package com.kgcx.dbutils.aspect;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.kgcx.common.bean.ReturnData;
import com.kgcx.common.exception.BusinessException;
import feign.codec.DecodeException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author wuganglin
 * Created by Administrator on 2017/2/20.
 */
@Component
@Aspect
@SuppressWarnings("unchecked")
public class PageInfoAspect {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());


    @Pointcut("execution(public * com.kgcx.*.controller.*.*(..)) ")
    public void pointcut() {
    }

    //应用周围通知
    @Around("pointcut()")
    public Object doAround(ProceedingJoinPoint call) {
        try {
            Object result = call.proceed();
            buildPageInfo(result);
            return result;
        } catch (Throwable e) {
            if (e instanceof BusinessException) {
                BusinessException ex = (BusinessException) e;
                throw ex;
            }
            if (e instanceof DecodeException) {
                return new ReturnData("-1", e.getMessage());
            }
            logger.error("内部错误", e);
            return new ReturnData("-1", "内部错误！");
        }
    }

    /**
     * 分页器分页信息放入返回对象
     *
     * @param result
     */
    private void buildPageInfo(Object result) {
        if (null != result && result instanceof ReturnData) {
            ReturnData rd = (ReturnData) result;
            Object data = rd.getData();
            if (null != data && data instanceof Page) {
                Page page = (Page) data;
                PageInfo pageInfo = new PageInfo(page);
                rd.setPageNum(pageInfo.getPageNum());
                rd.setPages(pageInfo.getPages());
                rd.setTotal((int) pageInfo.getTotal());
            }
        }
    }

}
